package cn.alm.serviceorder.exceptionhandler;

import cn.alm.serviceorder.common.CR;
import com.alibaba.csp.sentinel.adapter.spring.webmvc_v6x.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;

@Component
public class ProjectBlockExceptionHandler implements BlockExceptionHandler {

    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String s, BlockException e) throws Exception {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = httpServletResponse.getWriter();
        httpServletResponse.setStatus(429);
        CR cr = new CR();
        cr.setCode(500);
        cr.setMessage("被Sentinel限流了！");
//        cr.setData(null);
        writer.write(objectMapper.writeValueAsString(cr));
        writer.flush();
        writer.close();
    }
}
